package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager.WakeLock;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.adapter.CommentAdapter;
import com.jdy.haoduoai.enums.DownloadState;
import com.jdy.haoduoai.enums.MediaState;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.CarlaClassicVo;
import com.jdy.haoduoai.model.CommentItem;
import com.jdy.haoduoai.model.LeHotDynamicItem;
import com.jdy.haoduoai.model.LePlaybackRecordItem;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.rx.util.async.Async;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.DateUtils;
import com.jdy.haoduoai.util.FileUtils;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.RoundImageView;
import com.jdy.haoduoai.widget.CustomCommonDialog;
import com.jdy.haoduoai.widget.progressbar.DonutProgress;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;

//import com.jdy.haoduoai.R;

@SuppressLint({ "SimpleDateFormat", "HandlerLeak", "InflateParams" })
public class ShareStoryDetailInfoActivity extends BaseActivity implements
    OnClickListener, Callback {

  @InjectView(id = R.id.toplays, click = true)
  private RelativeLayout shareplaylayout;
  @InjectView(id = R.id.back, click = true)
  private ImageButton back;
  @InjectView(id = R.id.shareimgs)
  private ImageView shareimg;
  @InjectView(id = R.id.sv_video)
  private SurfaceView sv_video;
  @InjectView(id = R.id.playbtn, click = true)
  private Button playbtn;
  @InjectView(id = R.id.download_progress)
  private DonutProgress donutProgress;
  @InjectView(id = R.id.endtime)
  private TextView endtime;
  @InjectView(id = R.id.usetime)
  private TextView usetime; // 已经播放时间
  @InjectView(id = R.id.seek)
  private SeekBar seekBar;
  @InjectView(id = R.id.headicon)
  private RoundImageView headicon;
  @InjectView(id = R.id.editor)
  private TextView editor;
  @InjectView(id = R.id.playtimes)
  private TextView playtimes;
  @InjectView(id = R.id.tv_share, click = true)
  private TextView tv_share;
  @InjectView(id = R.id.releasetime)
  private TextView releasetime; // 发布时间
  @InjectView(id = R.id.zannums, click = true)
  private TextView zannums;
  @InjectView(id = R.id.tellone, click = true)
  private Button tellone;
  @InjectView(id = R.id.pushto, click = true)
  private Button pushto;
  @InjectView(id = R.id.commentnums)
  private TextView commentnums;
  @InjectView(id = R.id.writecomment, click = true)
  private Button writecomment;
  @InjectView(id = R.id.commentlist)
  private ListView listView;

  private SurfaceHolder surfaceHolder;
  private MediaPlayer mp4Player, mp3Player;
  private MediaState mMediaState = MediaState.Downloaded;
  private String userComments;
  private Thread mDownloadingThread;
  private boolean trafficWarning;

  private DownloadState mDownloadState = DownloadState.None;
  private String video_url, mp3_url, cover, avatar, username;
  private int idStory, uid, zans, playnums, playtime;
  private LeHotDynamicItem mDetailInfoItem = null;
  private LePlaybackRecordItem mLePlaybackRecordItem;
  private DisplayImageOptions options;
  private LeUser mLeUser;
  private int fileSize;
  private CommentAdapter adapter;
  private ArrayList<CommentItem> mList;
  boolean isPause; // 是否已经暂停了
  private Subscription mSubscription;

  private String filePath; // mp4 文件路径
  private URL downloadurl = null;
  private int downloadSize;
  private WakeLock mWakeLock;

  private int currentMP4Position, currentMP3Position;

  @Override
  @SuppressLint("InflateParams")
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.shareitemdetail);
    hideTitleView();
    initialize();
    initListener();
    initHandler();
    getComments();
    setVideoHeight();
  }

  private void setVideoHeight() {
    DisplayMetrics metrics = getResources().getDisplayMetrics();

    int w = metrics.widthPixels;
    int h = w * 3 / 4;

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, h);
    shareplaylayout.setLayoutParams(params);

    RelativeLayout.LayoutParams seekBarParams = (RelativeLayout.LayoutParams) seekBar
        .getLayoutParams();
    seekBarParams.topMargin = h - Tools.getPixelByDip(this, 10);
    seekBar.setLayoutParams(seekBarParams);
  }

  @Override
  public void onPause() {
    super.onPause();

    MobclickAgent.onPause(this);

    if (mWakeLock != null) {
      mWakeLock.release();
    }

    if (mDownloadState.equals(DownloadState.Begin)
        || mDownloadState.equals(DownloadState.Downloading)) {
      mDownloadingThread.interrupt();

      String dubName;
      if (mDetailInfoItem != null) {
        dubName = mDetailInfoItem.dub_name;
      } else {
        dubName = mLePlaybackRecordItem.name;
      }

      String filePath = Environment.getExternalStorageDirectory()
          + "/haoduoai/dub/" + dubName + ".mp4";
      File file = new File(filePath);
      if (file.exists()) {
        file.delete();
      }
    }

    if (mp4Player != null && mp4Player.isPlaying()) {
      mp4Player.pause();
      currentMP4Position = mp4Player.getCurrentPosition();
      isPause = true;
    }

    if (mp3Player != null && mp3Player.isPlaying()) {
      mp3Player.pause();
      currentMP3Position = mp3Player.getCurrentPosition();
    }

  }

  @Override
  public void onResume() {
    super.onResume();

    MobclickAgent.onResume(this);

    if (mWakeLock != null) {
      mWakeLock.acquire();
    }
  }

  private void getComments() {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          try {
            JSONObject json = new JSONObject(result.data);
            String data = json.optString("data");
            JSONArray array = new JSONArray(data);
            if (mList.size() > 0)
              mList.clear();
            for (int i = 0; i < array.length(); i++) {
              JSONObject obj = ((JSONObject) array.opt(i));

              if (Tools.isNotEmpty(obj.toString())) {
                CommentItem item = JsonSerializer.getInstance().deserialize(
                    obj.toString(), CommentItem.class);
                mList.add(item);
              }

            }
            setCommentAdapter();
          } catch (Exception e) {
          }
        } else {
          toastShow(result.data);
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put("category", "album");

        if (Tools.isNotEmpty(mDetailInfoItem)) {
          param_.put("foreign_id", mDetailInfoItem.id);
        } else if (Tools.isNotEmpty(mLePlaybackRecordItem)) {
          param_.put("foreign_id", mLePlaybackRecordItem.entity_id);
        }

        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        return HttpUtils.startRequest(HttpUtils.HOST_API
            + HttpUtils.GET_COMMENT_LIST, param_, HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  private void setCommentAdapter() {
    if (adapter == null) {
      adapter = new CommentAdapter(this, mList);
      listView.setAdapter(adapter);
      initEmptyView(R.drawable.no_comment);
    } else {
      adapter.notifyDataSetChanged();
    }
    if (mList != null)
      commentnums.setText("共" + mList.size() + "条评论");
    else {
      commentnums.setText("共0条评论");
    }
  }

  private void initEmptyView(int resId) {
    LinearLayout emptyView = new LinearLayout(this);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    emptyView.setOrientation(LinearLayout.VERTICAL);
    emptyView.setGravity(Gravity.CENTER);
    emptyView.setLayoutParams(params);

    LinearLayout.LayoutParams params_image = new LinearLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    ImageView image_empty = new ImageView(this);
    image_empty.setLayoutParams(params_image);
    image_empty.setScaleType(ScaleType.CENTER_INSIDE);
    image_empty.setImageResource(resId);
    emptyView.addView(image_empty);

    ((ViewGroup) listView.getParent()).addView(emptyView, params);
    listView.setEmptyView(emptyView);
  }

  private void initListener() {
    seekBar.setOnSeekBarChangeListener(new SeekBarChangeEvent());
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (mSubscription != null) {
      mSubscription.unsubscribe();
    }
    if (handler != null) {
      handler.removeCallbacksAndMessages(null);
      handler = null;
    }
  }

  private void initHandler() {
    handler = new Handler() {
      @SuppressWarnings("deprecation")
      @Override
      public void handleMessage(Message msg) {
        super.handleMessage(msg);

        if (!Thread.currentThread().isInterrupted()) {
          switch (msg.what) {
          case 0:
            // 下载开始
            donutProgress.setMax(100);
            donutProgress.setVisibility(View.VISIBLE);
            playbtn.setVisibility(View.GONE);
            shareimg.setAlpha(0);
            mDownloadState = DownloadState.Begin;
            break;
          case 1:
            // 下载中
            int currentProgress = (int) (((double) downloadSize / (double) fileSize) * 100);
            donutProgress.setProgress(currentProgress);
            int currentAlpha = (int) ((double) (currentProgress * 255) / (double) 100);
            shareimg.setAlpha(currentAlpha);
            mDownloadState = DownloadState.Downloading;
            break;
          case 2:
            // 下载完成
            mDownloadState = DownloadState.Finished;
            toastShow("下载完毕，再次点击【开始】播放");
            donutProgress.setVisibility(View.GONE);
            playbtn.setVisibility(View.VISIBLE);
            mMediaState = MediaState.Downloaded;
            break;
          case 5:
            usetime.setText(DateUtils.getTime(playtime / 1000));
            seekBar.setProgress(playtime / 1000);
            break;
          case 10:
            toastShow("下载失败，请检查磁盘空间或者网络");
            donutProgress.setVisibility(View.GONE);
            break;
          default:
            break;
          }
        }

      }
    };
  }

  private String getElapseTime(String createdTime) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
      Date oldDate = formatter.parse(createdTime);
      Date nowDate = new Date();
      long diff = nowDate.getTime() - oldDate.getTime();
      long seconds = diff / 1000;
      long minutes = seconds / 60;
      long hours = minutes / 60;
      long days = hours / 24;
      if (seconds < 60) {
        return seconds + "秒前";
      } else if (seconds < 3600) {
        return minutes + "分钟前";
      } else if (seconds >= 3600 && seconds < 86400) {
        return hours + "小时前";
      } else {
        return days + "天前";
      }

    } catch (ParseException e) {
      e.printStackTrace();
    }
    return null;
  }

  private void initialize() {
    tellone.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    pushto.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);

    options = new DisplayImageOptions.Builder().cacheInMemory(true) // 缓存
        .bitmapConfig(Bitmap.Config.RGB_565) // 图片格式
        .build();
    mLeUser = ((LeXiaoXiaoBanApp) this.getApplication()).getUser();
    mList = new ArrayList<>();
    if (getIntent().getSerializableExtra("rank_map") != null) {
      mDetailInfoItem = (LeHotDynamicItem) getIntent().getSerializableExtra(
          "rank_map");

      if (Tools.isNotEmpty(mDetailInfoItem)) {
        if (mDetailInfoItem.member_id != null) {
          uid = mDetailInfoItem.id;
        }
        if (mDetailInfoItem.member_avatar != null) {
          avatar = mDetailInfoItem.member_avatar;
        }
        if (mDetailInfoItem.created_at != null) {
          releasetime.setText(getElapseTime(mDetailInfoItem.created_at));
        } else {
          releasetime.setText("");
        }

        if (Tools.isNotEmpty(mDetailInfoItem.dub_cover)) {
          cover = mDetailInfoItem.dub_cover;
        }
      }

      idStory = mDetailInfoItem.id;

      if (mDetailInfoItem.member_nickname != null) {
        username = mDetailInfoItem.member_nickname;
      }

      playnums = mDetailInfoItem.play_count;

      if (Tools.isNotEmpty(mDetailInfoItem.merge_av)
          && !mDetailInfoItem.merge_av.endsWith("avi")) {
        video_url = HttpUtils.HOST_RESOURCE + mDetailInfoItem.merge_av;
      } else {
        video_url = mDetailInfoItem.story_template;
        if (Tools.isEmpty(video_url)) {
          video_url = mDetailInfoItem.av;
        } else {
          mp3_url = mDetailInfoItem.av;
        }
      }

      ImageLoader.getInstance().displayImage(avatar, headicon, options);
      ImageLoader.getInstance().displayImage(cover, shareimg, options);

      editor.setText(username);

      if (mDetailInfoItem.following) {
        Drawable drawable = getResources().getDrawable(R.drawable.focused_icon);
        editor.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable,
            null);
      } else {
        editor.setOnClickListener(new OnClickListener() {
          @Override
          public void onClick(View v) {
            // 关注
            Async.start(new Func0<ResponseResult>() {

              @Override
              public ResponseResult call() {
                LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
                if (lu == null) {
                  lu = Tools.restoreLeUser();
                }

                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                param_.put(HttpUtils.TAG_SNO_I, lu.sno);
                param_.put("following_id", mDetailInfoItem.member_id);

                return HttpUtils.startRequest(HttpUtils.API_URL
                    + HttpUtils.FOLLOW_SOMEONE_POST, param_,
                    HttpUtils.TAG_POST_REQUEST);
              }
            }).filter(new Func1<ResponseResult, Boolean>() {

              @Override
              public Boolean call(ResponseResult arg0) {

                return arg0 != null && Tools.isNotEmpty(arg0)
                    && arg0.isSuccess();
              }
            }).doOnCompleted(new Action0() {
              @Override
              public void call() {
                // TODO
              }
            }).subscribe(new Action1<ResponseResult>() {

              @Override
              public void call(ResponseResult arg0) {
                // TODO
              }
            });

          }
        });
      }

      if (Tools.isNotEmpty(mDetailInfoItem.member_id)
          && mDetailInfoItem.member_id.contains(mLeUser.id)) {
        editor.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
      }

      zannums.setText(mDetailInfoItem.like + "");
      playtimes.setText("播放" + playnums + "次");

      filePath = Environment.getExternalStorageDirectory()
          + "/haoduoai/dub/" + mDetailInfoItem.dub_name + ".mp4";

    } else {
      fromRecentPlay();
    }
  }

  private void fromRecentPlay() {
    if (getIntent().getSerializableExtra("recentplayitem") != null) {
      mLePlaybackRecordItem = (LePlaybackRecordItem) getIntent()
          .getSerializableExtra("recentplayitem");

      if (mLePlaybackRecordItem.catalog.contains("story")) {
        video_url = mLePlaybackRecordItem.story_template;
      } else if (mLePlaybackRecordItem.catalog.contains("book")) {
        video_url = mLePlaybackRecordItem.av;
      }

      if (Tools.isNotEmpty(mLePlaybackRecordItem)) {
        if (mLePlaybackRecordItem.created_at != null) {
          releasetime.setText(getElapseTime(mLePlaybackRecordItem.created_at));
        } else {
          releasetime.setText("");
        }

        if (Tools.isNotEmpty(mLePlaybackRecordItem.cover)) {
          cover = mLePlaybackRecordItem.cover;
        }
      }

      idStory = mLePlaybackRecordItem.entity_id;

      ImageLoader.getInstance().displayImage(avatar, headicon, options);
      ImageLoader.getInstance().displayImage(cover, shareimg, options);

      editor.setText(username);

      filePath = Environment.getExternalStorageDirectory()
          + "/haoduoai/dub/" + mLePlaybackRecordItem.name + ".mp4";
    }
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.tv_share:
      Intent intent = new Intent(this, SharePopupWindow.class);
      intent.putExtra("pic", cover);
      intent.putExtra("name", mDetailInfoItem.dub_name);
      intent.putExtra("id", mDetailInfoItem.id); // 音频
      intent.putExtra("share_data", "配音故事");

      startActivity(intent);

      break;
    case R.id.back:
      finish();
      break;
    case R.id.toplays:
      if (sv_video.isShown()) {
        if (mMediaState.equals(MediaState.Playing)) {// precondition must be
          mMediaState = MediaState.Pause;
          playbtn.setVisibility(View.VISIBLE);

          if (mp4Player != null && mp4Player.isPlaying()) {
            mp4Player.pause();
            currentMP4Position = mp4Player.getCurrentPosition();
            isPause = true;
          }

          if (mp3Player != null && mp3Player.isPlaying()) {
            mp3Player.pause();
            currentMP3Position = mp3Player.getCurrentPosition();
          }

        } else if (mMediaState.equals(MediaState.Pause)) {
          mMediaState = MediaState.Playing;
          playbtn.setVisibility(View.GONE);

          if (mp4Player != null) {
            mp4Player.start();
          }
        }
      } else {
      }
      break;
    case R.id.playbtn:
      File file = new File(filePath);
      if (!file.exists()) {
        CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
            ShareStoryDetailInfoActivity.this).setTitle("提示")
            .setMessage("还没下载该故事，是否现在开始下载？")
            .setNegativeButton("否", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
              }
            }).setPositiveButton("是", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                if (!trafficWarning
                    && !Tools
                        .isWifiConnected(ShareStoryDetailInfoActivity.this)
                    && handler != null) {
                  trafficWarning = true;
                  handler.post(new Runnable() {

                    @Override
                    public void run() {
                      if (isFinishing()) {
                        return;
                      }

                      CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
                          ShareStoryDetailInfoActivity.this)
                          .setTitle("温馨提示")
                          .setMessage("您当前使用移动网络，继续下载将产生流量费用，敬请留意")
                          .setNegativeButton("继续下载",
                              new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                    int which) {
                                  mDownloadingThread = new Thread() {
                                    @Override
                                    public void run() {
                                      try {
                                        downloadFile(video_url,
                                            "haoduoai/dub/",
                                            mDetailInfoItem.dub_name + ".mp4");
                                      } catch (IOException e) {
                                        e.printStackTrace();
                                      }
                                    }
                                  };
                                  mDownloadingThread.start();
                                }
                              })
                          .setPositiveButton("取消",
                              new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                    int which) {
                                  trafficWarning = false;
                                  dialog.dismiss();
                                }
                              });

                      if (!isFinishing()) {
                        cdb.create().show();
                      }
                    }
                  });
                } else {
                  mDownloadingThread = new Thread() {
                    @Override
                    public void run() {
                      try {
                        int rCode = 0;
                        if (Tools.isNotEmpty(mDetailInfoItem)) {
                          rCode = downloadFile(video_url, "haoduoai/dub/",
                              mDetailInfoItem.dub_name + ".mp4");
                        } else if (Tools.isNotEmpty(mLePlaybackRecordItem)) {
                          rCode = downloadFile(video_url, "haoduoai/dub/",
                              mLePlaybackRecordItem.name + ".mp4");
                        }

                        if (rCode == -1) {
                          toastShow("下载失败!");
                        }
                      } catch (IOException e) {
                        e.printStackTrace();
                      }
                    }
                  };
                  mDownloadingThread.start();
                  dialog.dismiss();
                }

              }
            });

        if (!isFinishing()) {
          cdb.create().show();
        }
      } else {
        if (mMediaState == MediaState.Pause) {
          mMediaState = MediaState.Playing;
          playbtn.setVisibility(View.GONE);

          if (Tools.isNotEmpty(mp3_url) && mp3Player != null) {
            mp3Player.start();
          }

          if (mp4Player != null) {
            mp4Player.start();
            new Thread(new UIUpdateThread()).start();
          }
        } else {
          play();
        }
      }
      break;
    case R.id.zannums: // 点赞
      zanvideo(idStory);
      break;
    case R.id.tellone:

      if (mDetailInfoItem != null) {
        if (Tools.isNotEmpty(mDetailInfoItem.catalog)
            && mDetailInfoItem.catalog.equalsIgnoreCase("book")) {
          // CartoonVo cvo = new CartoonVo();
          // cvo.setName(mDetailInfoItem.dub_name);
          // cvo.setId(mDetailInfoItem.entity_id);
          // cvo.setCover(mDetailInfoItem.dub_cover);
          //
          // Intent intent = new Intent(this, StoryBookActivity.class);
          // Bundle bundle = new Bundle();
          // bundle.putSerializable("illustratedstory", cvo);
          // intent.putExtras(bundle);
          // startActivity(intent);

        } else {
          toRecordActivity(this, mDetailInfoItem.entity_id);
        }
      } else if (mLePlaybackRecordItem != null) {
        if (Tools.isNotEmpty(mLePlaybackRecordItem.catalog)
            && mLePlaybackRecordItem.catalog.equalsIgnoreCase("book")) {
          // CartoonVo cvo = new CartoonVo();
          // cvo.setName(mLePlaybackRecordItem.name);
          // cvo.setId(mLePlaybackRecordItem.entity_id);
          // cvo.setCover(mLePlaybackRecordItem.cover);
          //
          // Intent intent = new Intent(this, StoryBookActivity.class);
          // Bundle bundle = new Bundle();
          // bundle.putSerializable("illustratedstory", cvo);
          // intent.putExtras(bundle);
          // startActivity(intent);

        } else {
          toRecordActivity(this, mLePlaybackRecordItem.entity_id);
        }
      }

      break;
    case R.id.pushto: // push to device
      playvideo(idStory);
      break;
    case R.id.writecomment: // write comment
      View view = LayoutInflater.from(this).inflate(
          R.layout.writecommentdialog, null);
      final EditText editText = (EditText) view.findViewById(R.id.comments);
      CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(this)
          .setContentView(view)
          .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
              dialog.dismiss();
            }
          }).setPositiveButton("发表", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
              if (TextUtils.isEmpty(editText.getText().toString().trim())) {
                toastShow("请填写评论后再发表");
              } else {
                userComments = editText.getText().toString();
                addComments();
                dialog.dismiss();
              }
            }
          });

      if (!isFinishing()) {
        cdb.create().show();
      }
      break;
    default:
      break;
    }

  }

  private void toRecordActivity(final Context context, final int storyId) {

    new AsyncTask<Void, Void, ResponseResult>() {
      @Override
      protected void onPostExecute(ResponseResult result) {
        if (Tools.isNotEmpty(result) && result.isSuccess()) {
          CarlaClassicVo ccv = JsonSerializer.getInstance().deserialize(
              result.data, CarlaClassicVo.class);

          Intent recode = new Intent();
          Bundle bundle = new Bundle();
          bundle.putSerializable("carlaclassic", ccv);
          recode.putExtras(bundle);
          recode.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          recode.setClass(context, RecordActivity2.class);

          context.startActivity(recode);
        }
      }

      @Override
      protected ResponseResult doInBackground(Void... params) {

        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        if (lu == null) {
          lu = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/catalog/story/" + storyId, param_,
            HttpUtils.TAG_GET_REQUEST);

      }

    }.execute();

  }

  // public String getName(String url) {
  // String[] out = null;
  // try {
  // out = URLDecoder.decode(url, "UTF-8").split("/");
  // } catch (UnsupportedEncodingException e) {
  // e.printStackTrace();
  // }
  // String path = Environment.getExternalStorageDirectory()
  // + "/haoduoai/share/" + out[out.length - 1];
  // return path;
  // }

  private void playvideo(final int sid) {
    new CustomAsyncTask(ShareStoryDetailInfoActivity.this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          toastShow("已推送到设备播放");
//          if (LeConfig.isDeviceConnect) {
//            toastShow("已推送到设备播放");
//          } else {
//            toastShow("未连接到设备，请检查设备联网情况！");
//          }

        } else {
          LeConfig.isDeviceConnect = false;
          toastShow("设备不在线");
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {

        int volume = -1, minutes = -1;

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
        param_.put(HttpUtils.TAG_ACTION_I, "play");
        //param_.put("mode", "im");

        if (mDetailInfoItem != null) {
         /* if (Tools.isNotEmpty(mDetailInfoItem.catalog)
              && mDetailInfoItem.catalog.equalsIgnoreCase("book")) {
            param_.put(HttpUtils.TAG_OPERATION_I, "book");
          } else */{
            param_.put(HttpUtils.TAG_OPERATION_I, "dub");
          }
        } else {
         /* if (Tools.isNotEmpty(mLePlaybackRecordItem.catalog)
              && mLePlaybackRecordItem.catalog.equalsIgnoreCase("book")) {
            param_.put(HttpUtils.TAG_OPERATION_I, "book");
          } else */{
            param_.put(HttpUtils.TAG_OPERATION_I, "dub");
          }
        }

        param_.put(HttpUtils.TAG_PLAY_MODE, String.valueOf(LeConfig.PlayMode));

        if (sid != -1) {
          param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(sid));
        }
//        if (uid != -1) {
//          param_.put(HttpUtils.TAG_UID_I, String.valueOf(uid));
//        }
        if (volume != -1) {
          param_.put(HttpUtils.TAG_VOLUME, String.valueOf(volume));
        }
        if (minutes != -1) {
          param_.put(HttpUtils.TAG_MINUTE_I, String.valueOf(minutes));
        }
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
            HttpUtils.TAG_GET_REQUEST);

      }
    }).execute();
  }

  private void zanvideo(final int sid) {
    new CustomAsyncTask(ShareStoryDetailInfoActivity.this, new IAsyncTask() {

      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {

          // Message message = new Message();
          // message.what = 9;
          // handler.sendMessage(message);

          if (!result.data.contains("已经点过赞了")) {
            mDetailInfoItem.like = mDetailInfoItem.like + 1;
            zannums.setText(mDetailInfoItem.like + "");
          }
        }

        if (Tools.isNotNullStr(result.data)) {
          toastShow(result.data);
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
        param_.put("dub_id", idStory);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/member/dub/like", param_, HttpUtils.TAG_POST_REQUEST);
      }
    }).execute();
  }

  @SuppressWarnings({ "deprecation", "resource" })
  public int downloadFile(String urlStr, String path, String fileName)
      throws IOException {
    if (Tools.isEmpty(urlStr))
      return -1;
    downloadurl = new URL(URLEncoder.encode(urlStr).replace("%3A", ":")
        .replace("%2F", "/"));
    HttpURLConnection urlconn = (HttpURLConnection) downloadurl
        .openConnection();
    InputStream inputstream = urlconn.getInputStream();
    OutputStream outputStream = null;
    try {
      FileUtils fileutils = new FileUtils();
      if (fileutils.isFileExist(path + fileName)) {
        return 1;
      } else {
        if (!fileutils.isFileExist(path)) {
          fileutils.createSDDir(path);
        }
        File file = fileutils.createSDFile(path + fileName);
        outputStream = new FileOutputStream(file);
        this.fileSize = urlconn.getContentLength();
        handler.sendEmptyMessage(0);
        byte buffer[] = new byte[4 * 1024];
        int temp = 0;
        downloadSize = 0;
        while ((temp = inputstream.read(buffer)) != -1) {
          outputStream.write(buffer, 0, temp);
          downloadSize += temp;
          System.out.println("=======downloadSize=====" + downloadSize);
          handler.sendEmptyMessage(1);
        }

        outputStream.flush();
        handler.sendEmptyMessage(2);
        if (file == null)
          return -1;
        inputstream.close();
        outputStream.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
      return -1;
    }
    return 0;
  }

  private void addComments() {
    showloading("");
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        dismissLoading();
        if (result.isSuccess()) {
          toastShow("发表成功");
          getComments();
        } else {
          toastShow(result.data);
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put("category", "album");
        param_.put("comment", userComments);

        if (mDetailInfoItem != null) {
          param_.put("foreign_id", mDetailInfoItem.id);
        } else {
          param_.put("foreign_id", mLePlaybackRecordItem.entity_id);
        }

        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        return HttpUtils.startRequest(HttpUtils.HOST_API
            + HttpUtils.GET_COMMENT_LIST, param_, HttpUtils.TAG_POST_REQUEST);
      }
    }).execute();
  }

  /**
   * 播放
   */
  @SuppressWarnings("deprecation")
  private void play() {
    if (isPause) {
      if (Tools.isNotEmpty(mp3_url) && mp3Player != null) {
        mp3Player.seekTo(currentMP3Position);
        mp3Player.start();
      }

      if (mp4Player != null) {
        mp4Player.seekTo(currentMP4Position);
        mp4Player.start();
      }
      // 变为false
      isPause = false;
    } else {
      // 判断视频 是否为播放状态
      if (mp4Player != null) {
        if (mp4Player.isPlaying()) {
          System.out.println("视频处于播放状态");
        }
      } else {
        playbtn.setVisibility(View.GONE);
        sv_video.setVisibility(View.VISIBLE);
        surfaceHolder = sv_video.getHolder();
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        surfaceHolder.addCallback(this);
      }
    }
  }

  // public void resetVideo() {
  // if (mp4Player != null && mp4Player.isPlaying()) {
  // mp4Player.seekTo(0);
  // mp4Player.start();
  // }
  // }

  // public void pasueVideo() {
  // if (mp4Player != null && mp4Player.isPlaying()) {
  // mp4Player.pause();
  // // 记录这个位置
  // currentMP4Position = mp4Player.getCurrentPosition();
  // // 标识 这视频 会被暂停
  // isPause = true;
  // }
  // }

  // public void stopVideo() {
  // if (mp4Player != null && mp4Player.isPlaying()) {
  // mp4Player.stop();
  // mp4Player.release();
  // mp4Player = null;
  // // 暂停标识
  // isPause = false;
  // }
  // }

  /**
   * 调用此方法输入所要转换的时间戳输入例如（1402733340）输出（"2014年06月14日16时09分"）
   * 
   * @param time
   * @return
   */
  // public String timet(String time) {
  // SimpleDateFormat sdr = new SimpleDateFormat("HH:mm");
  // int i = Integer.parseInt(time);
  // String times = sdr.format(new Date(i * 1000L));
  // return times;
  // }

  @Override
  public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
    Log.i("通知", "surfaceHolder被改变了");
  }

  @Override
  public void surfaceCreated(SurfaceHolder arg0) {
    Log.i("通知", "surfaceHolder被create了");

    new AsyncTask<Void, Void, Void>() {

      @Override
      protected void onPreExecute() {
        playbtn.setVisibility(View.GONE);
      }

      @Override
      protected Void doInBackground(Void... params) {
        mp4Player = new MediaPlayer();
        mp4Player.setDisplay(surfaceHolder);
        mp4Player.setOnCompletionListener(new OnCompletionListener() {
          @Override
          public void onCompletion(MediaPlayer arg0) {
            if (mp4Player != null) {
              mp4Player.release();
              mp4Player = null;
            }
          }
        });
        mp4Player.setOnErrorListener(new OnErrorListener() {
          @Override
          public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
            if (mp4Player != null) {
              mp4Player.release();
              mp4Player = null;
            }
            return false;
          }
        });
        try {
          mp4Player.setDataSource(filePath);
          mp4Player.prepare();
          mp4Player.seekTo(currentMP4Position);
          mp4Player.start();
          // mp4Player.setVolume(0, 0);
          if (mp3Player != null) {
            mp3Player.release();
            mp3Player = null;
          }
          isPause = false;

          if (Tools.isNotEmpty(mp3_url)) {
            mp3Player = new MediaPlayer();
            mp3Player.setOnCompletionListener(new OnCompletionListener() {
              @Override
              public void onCompletion(MediaPlayer arg0) {
                if (mp3Player != null) {
                  mp3Player.release();
                  mp3Player = null;
                }
              }
            });
            mp3Player.setOnErrorListener(new OnErrorListener() {
              @Override
              public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
                if (mp3Player != null) {
                  mp3Player.release();
                  mp3Player = null;
                }
                return false;
              }
            });
            mp3Player.setDataSource(mp3_url);
            mp3Player.prepare();
            mp3Player.seekTo(currentMP3Position);
            mp3Player.start();
          }

          mMediaState = MediaState.Playing;
        } catch (Exception e) {
          e.printStackTrace();
        }
        return null;
      }

      @Override
      protected void onPostExecute(Void result) {

        if (Tools.isNotEmpty(mp4Player)) {
          seekBar.setMax(mp4Player.getDuration() / 1000);
          endtime.setText(" / "
              + DateUtils.getTime(mp4Player.getDuration() / 1000));
          new Thread(new UIUpdateThread()).start();
        }
      }

    }.execute((Void[]) null);

  }

  private Thread mUIUpdateThread;

  @Override
  public void surfaceDestroyed(SurfaceHolder arg0) {
    Log.i("通知", "surfaceHolder被销毁了");

    if (mp4Player != null && mp4Player.isPlaying()) {
      mp4Player.stop();
    }

    if (mp3Player != null && mp3Player.isPlaying()) {
      mp3Player.stop();
    }
  }

  private class UIUpdateThread implements Runnable {
    long time = 500; // 滚动速度

    @Override
    public void run() {
      while (mp4Player != null && mp4Player.isPlaying()) {
        playtime = mp4Player.getCurrentPosition();
        handler.sendEmptyMessage(5);
        try {
          Thread.sleep(time);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }

  private class SeekBarChangeEvent implements OnSeekBarChangeListener {
    @Override
    public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
    }

    @Override
    public void onStartTrackingTouch(SeekBar arg0) {
      // 开始拖动进度条
      // isChanging = true;
    }

    @Override
    public void onStopTrackingTouch(SeekBar arg0) {
      // 停止拖动进度条
      if (mp3Player != null) {
        mp3Player.seekTo(arg0.getProgress());
      }

      if (mp4Player != null) {
        mp4Player.seekTo(arg0.getProgress());
      }

      // isChanging = false;
      if (mp3Player != null && mp3Player.isPlaying()) {
        mp3Player.seekTo(arg0.getProgress() * 1000);
        mp3Player.start();
      }
      if (mp4Player != null && mp4Player.isPlaying()) {
        mp4Player.seekTo(arg0.getProgress() * 1000);
        mp4Player.start();
      }
    }
  }

}
